package org.realteam.base.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

/**
 * @author Harry
 * 
 * @version 1.0 Created On：2011-12-10 下午5:51:27
 * 
 */

@Repository
public class BaseDao implements ApplicationContextAware {

	protected ApplicationContext applicationContext;

	@Autowired
	private SessionFactory sessionFactory;

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.applicationContext = context;
	}
	
	public <T> List<T> find(String queryString) throws DataAccessException {
		return find(queryString, (Object[]) null);
	}

	public <T> List<T> find(String queryString, Object value) throws DataAccessException {
		return find(queryString, new Object[] { value });
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> find(final String queryString, final Object[] values) {
		Query query = getSession().createQuery(queryString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return query.list();
	}

	public Object load(Serializable oid, Class<?> clazz) {
		Object o = null;
		o = getSession().get(clazz, oid);

		return o;
	}

	public void refresh(Object object) {
		getSession().refresh(object);
	}

	public void flush() {
		getSession().flush();
	}

	public void clear() {
		getSession().clear();
	}

	public Object merge(Object object) {
		return getSession().merge(object);
	}

	public void save(Object object) {
		getSession().save(object);
	}

	public void saveOrUpdate(Object object) {
		getSession().saveOrUpdate(object);
	}

	public void delete(Object po) {
		getSession().delete(po);
	}
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

}
